package com.api.controller;

import com.api.annotation.Login;
import com.api.common.constant.Constant;
import com.api.common.page.PageData;
import com.api.common.utils.ConvertUtils;
import com.api.common.utils.Result;
import com.api.entity.Item;
import com.api.entity.StarCollect;
import com.api.entity.dto.ItemDTO;
import com.api.entity.vo.CateVO;
import com.api.service.IStarCollectService;
import com.api.service.ItemService;
import com.api.service.UploadService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 岗位表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-08-12
 */
@RestController
@RequestMapping("/api/item")
@Tag(name = "接口")
@AllArgsConstructor
public class ItemController {

    private  final ItemService iItemService;
    private  final IStarCollectService iStarCollectService;
    @Autowired
    private UploadService uploadService;
    /**
     * 分页
     */
    @GetMapping("page")
    @Operation(summary = "分页")
    @Parameters({
            @Parameter(name = Constant.PAGE, description = "当前页码，从1开始", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.LIMIT, description = "每页显示记录数", in = ParameterIn.QUERY, required = true, ref = "int"),
            @Parameter(name = Constant.ORDER_FIELD, description = "排序字段", in = ParameterIn.QUERY, ref = "String"),
            @Parameter(name = Constant.ORDER, description = "排序方式，可选值(asc、desc)", in = ParameterIn.QUERY, ref = "String"),
            @Parameter(name = "cateName", description = "分类名称", in = ParameterIn.QUERY, ref = "String"),
            @Parameter(name = "title", description = "名称", in = ParameterIn.QUERY, ref = "String")
    })
    public Result<PageData<Item>> page(@RequestParam Map<String, Object> params){
        PageData<Item> page = iItemService.page(params);
        ArrayList<Item> res = new ArrayList<>();
        for (Item dto : page.getList()) {
            dto.setImg(uploadService.toAbsoluteUrl(dto.getImg()));
            res.add(dto);
        }
        return new Result<PageData<Item>>().ok(page);
    }




    @Login
    @PostMapping
    @Operation(summary = "保存")
    public Result save(@RequestBody Item dto) {
        dto.setImg(uploadService.deleteFile(dto.getImg()));
        iItemService.insert(dto);
        return new Result();
    }
    @Login
    @PutMapping("update")
    @Operation(summary = "修改")
    public Result update(@RequestBody Item dto) {
        dto.setImg(uploadService.deleteFile(dto.getImg()));
        iItemService.updateById(dto);
        return new Result();
    }

    @Login
    @DeleteMapping("{id}")
    @Operation(summary = "删除")
    public Result delete(@PathVariable("id") Long id) {
        iItemService.deleteById(id);
        return new Result();
    }
    /**
     * 详情
     */
    @GetMapping("{id}")
    @Operation(summary = "信息")
    public Result<Item> get(@PathVariable("id") Long id) {
        Item item = iItemService.selectById(id);
        item.setImg(uploadService.toAbsoluteUrl(item.getImg()));
        return new Result<Item>().ok(item);
    }
    /**
     * 浏览展示
     */
    @Login
    @GetMapping("view")
    @Operation(summary = "浏览展示")
    public Result< List<ItemDTO>> getBehaviorView(@RequestParam Integer type ,@RequestAttribute("userId") Long userId) {
        LambdaQueryWrapper<StarCollect> lwq = new LambdaQueryWrapper<>();
        if (type == 1){
            lwq.eq(StarCollect::getType,Constant.VIEW);
        }
        if (type == 2){
            lwq.eq(StarCollect::getType,Constant.STAR);
        }
        if (type == 3){
            lwq.eq(StarCollect::getType,Constant.COLLECT);
        }
        lwq.orderByAsc(StarCollect::getCreateTime);
        lwq.eq(StarCollect::getUserId,userId);
        List<StarCollect> list = iStarCollectService.list(lwq);
        List<ItemDTO> res = new ArrayList<>();
        for (StarCollect starCollect : list) {
            Item item = iItemService.selectById(starCollect.getItemId());
            if (item !=null){
                res.add(ConvertUtils.sourceToTarget(item, ItemDTO.class));
            }
        }
        return new Result< List<ItemDTO>>().ok(res);
    }


    /**
     * 浏览写入
     */
    @Login
    @GetMapping("view/{id}")
    @Operation(summary = "浏览写入")
    public Result UserBehaviorView(@PathVariable("id") Long id,@RequestAttribute("userId") Long userId) {
        //查询有没有
        LambdaQueryWrapper<StarCollect> lwq = new LambdaQueryWrapper<>();
        lwq.eq(StarCollect::getItemId, id);
        lwq.eq(StarCollect::getUserId, userId);
        if (iStarCollectService.exists(lwq)){return new Result();}
        StarCollect save = new StarCollect();
        save.setItemId(id);
        save.setUserId(userId);
        save.setType(Constant.VIEW);
        iStarCollectService.save(save);
        return new Result();
    }

    /**
     * 热门展示
     */

    @GetMapping("hot")
    @Operation(summary = "热门展示")
    public Result<List<ItemDTO>> hot() {
        //查询有没有
        LambdaQueryWrapper<StarCollect> lwq = new LambdaQueryWrapper<>();
        lwq.eq(StarCollect::getType,Constant.COLLECT);
        lwq.groupBy(StarCollect::getItemId);
        lwq.select(StarCollect::getItemId);
//        lwq.last("limit 9");
        List<Long> collectList = iStarCollectService.list(lwq).stream().map(StarCollect::getItemId).collect(Collectors.toList());
        ArrayList<ItemDTO> res = new ArrayList<>();
        for (Long aLong : collectList) {
            Item item = iItemService.selectById(aLong);
            if (item != null){
                res.add(ConvertUtils.sourceToTarget(item, ItemDTO.class));
                if (res.size() >=9){
                    break;
                }
            }
        }
        return new Result().ok(res);
    }


    /**
     * 侧边数据
     * @return
     */
    @GetMapping("like")
    @Operation(summary = "热门展示")
    public Result<List<Item>> like(@RequestParam  String type ,@RequestParam  Integer sum) {
        //查询有没有
        LambdaQueryWrapper<Item> lwq = new LambdaQueryWrapper<>();
        if (type.equals("collect")) {
            lwq.orderByDesc(Item::getCollectNumber);
        } else if (type.equals("ratings")) {
            lwq.orderByDesc(Item::getRatingsNumber);
        }
        lwq.last("LIMIT" + " " + sum); // 添加限制为10条数据
        List<Item> items = iItemService.selectList(lwq);

        for (Item item : items) {
            item.setImg(uploadService.toAbsoluteUrl(item.getImg()));
        }

        return new Result().ok(items);
    }


    /**
     * 分类展示
     * @return
     */
    @GetMapping("cateView")

    public Result<List<CateVO>> cate() {
        ArrayList<CateVO> res = new ArrayList<>();

        //查询分类数据
        ArrayList<String> cateName = new ArrayList<>();
        cateName.add("系统");
        cateName.add("古风");
        cateName.add("灵异");
        cateName.add("穿越");
        cateName.add("女神");
        cateName.add("战斗");
        cateName.add("修仙");
        cateName.add("权谋");
        for (String cate : cateName) {
            LambdaQueryWrapper<Item> lwq = new LambdaQueryWrapper<>();
            lwq.like(Item::getCateName,cate);
            lwq.orderByDesc(Item::getRatingsNumber);
            lwq.last("limit 10");
            List<Item> itemList = iItemService.selectList(lwq);
            CateVO vo = new CateVO();
            vo.setCateName(cate);
            for (Item item : itemList) {
                item.setImg(uploadService.toAbsoluteUrl(item.getImg()));
            }

            vo.setItems(itemList);
            res.add(vo);
        }
        return new Result().ok(res);
    }


    /**
     * 首页展示排行
     * @return
     */
    @GetMapping("cateNameView")
    @Operation(summary = "分类展示")
    public Result<List<CateVO>> cateNameView() {
        ArrayList<CateVO> res = new ArrayList<>();

        //查询分类数据
        ArrayList<String> cateName = new ArrayList<>();

        cateName.add("战斗");
        cateName.add("修仙");
        cateName.add("权谋");
        for (String cate : cateName) {
            LambdaQueryWrapper<Item> lwq = new LambdaQueryWrapper<>();
            lwq.like(Item::getCateName,cate);
            lwq.orderByDesc(Item::getView);
            lwq.last("limit 10");
            List<Item> itemList = iItemService.selectList(lwq);
            CateVO vo = new CateVO();
            vo.setCateName(cate);
            for (Item item : itemList) {
                item.setImg(uploadService.toAbsoluteUrl(item.getImg()));
            }

            vo.setItems(itemList);
            res.add(vo);
        }
        return new Result().ok(res);
    }


}
